package com.bootdo.system.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import sun.misc.BASE64Encoder;

/**
 * @author wh
 * @date 2018年2月25日 上午12:13:53 
*  @Description: 小程序二维码生成工具类
 */
public class QRCodeUtil {

	

	/**
	 * 获取商户二维码图片的base64串
	 * @param customerId
	 * @return
	 * @throws Exception
	 */
	public static String getCustomerQRCode(Long customerId) throws Exception {
        HttpGet httpGet = new HttpGet(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + "wxef0256a5461356df" + "&secret="
                        + "6dd00f32c68c4a245bad74ecc1dece29" );
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSON.parseObject(result);
        return  getPostUrl(jsons.getString("access_token"),"wxef0256a5461356df",customerId);
    }

	
	   /**
	 * @param access_token
	 * @param id
	 * @param customerId
	 * @return
	 * @throws Exception
	 */
	public static String getPostUrl(String access_token,String id,Long customerId) throws Exception {
	        String url ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
	         Map<String, Object> map = new HashMap<String, Object>();
	         map.put("path", "pages/kclist/kclist?customerId="+id);//你二维码中跳向的地址
	         map.put("width", "150");//图片大小
	         String jsonStr = "{\"path\":\"pages/index/index?customerId="+customerId+"\",\"width\":150}";
	         String  res= httpPostWithJSON(url + access_token, jsonStr,id, customerId);
	        return res;
	    }
	   
	   public static String httpPostWithJSON(String url, String json,String id, Long customerId)
               throws Exception {
           String result = null;
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpPost httpPost = new HttpPost(url);
           httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
     
           StringEntity se = new StringEntity(json);
           se.setContentType("application/json");
           se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                           "UTF-8"));
           httpPost.setEntity(se);
           HttpResponse response = httpClient.execute(httpPost);
           if (response != null) {
               HttpEntity resEntity = response.getEntity();
               if (resEntity != null) {
                      InputStream instreams = resEntity.getContent(); 
                      File saveFile = new File("temp.png");
                      if (!saveFile.exists()) {
                          saveFile.createNewFile();
                      }
                   saveToImgByInputStream(instreams, "temp.png");
                   result = getImageStr("temp.png");
                   saveFile.delete();
               }else {
            	   System.out.println("httpEntity为空,生成二维码失败");
               }
           }else {
        	   System.out.println("微信没有返回信息，生成二维码失败");
           }
           httpPost.abort();
           return result;
       } 
        
  /* @param instreams 二进制流
   * @param imgPath 图片的保存路径
   * @param imgName 图片的名称
   * @return
   *      1：保存正常
   *      0：保存失败
   */
  public static int saveToImgByInputStream(InputStream instreams,String imgName){
      int stateInt = 1;
      if(instreams != null){
          try {
              File file=new File(imgName);//可以是任何图片格式.jpg,.png等
              FileOutputStream fos=new FileOutputStream(file);
              byte[] b = new byte[1024];
              int nRead = 0;
              while ((nRead = instreams.read(b)) != -1) {
                  fos.write(b, 0, nRead);
              }
              fos.flush();
              fos.close();                
          } catch (Exception e) {
              stateInt = 0;
              e.printStackTrace();
          } finally {
              try {
               instreams.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
          }
      }
      return stateInt;
  }
  

//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
 public static String getImageStr(String imgFilePath) {
   byte[] data = null;
   // 读取图片字节数组
   try {
     InputStream in = new FileInputStream(imgFilePath);
     data = new byte[in.available()];
     in.read(data);
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   // 返回Base64编码过的字节数组字符串
   return Base64.getEncoder().encodeToString(data);
 }

}
